package com.cloudfun.campusshare.dao;

import cn.hutool.core.bean.BeanUtil;
import com.cloudfun.campusshare.common.model.vo.InvokeHistoryVO;
import com.cloudfun.campusshare.common.response.PageResult;
import com.cloudfun.campusshare.entity.InvokeHistoryEntity;
import com.cloudfun.campusshare.repo.InvokeHistoryEntityRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Huqin on 2019/12/27
 */
@Repository
public class InvokeHistoryDao {

    @Autowired
    private InvokeHistoryEntityRepo invokeHistoryEntityRepo;

    public PageResult<InvokeHistoryVO> search(String id, Pageable pageable) {
        Specification<InvokeHistoryEntity> specification = (root, query, criteriaBuilder) -> {
            return criteriaBuilder.equal(root.get("deviceId"), id);
        };
        Page<InvokeHistoryEntity> entityPage = invokeHistoryEntityRepo.findAll(specification, pageable);
        long totalElements = entityPage.getTotalElements();
        List<InvokeHistoryVO> content = entityPage.getContent().stream().map(deviceEntity -> {
            InvokeHistoryVO vo = new InvokeHistoryVO();
            BeanUtil.copyProperties(deviceEntity, vo);
            return vo;
        }).collect(Collectors.toList());
        PageResult<InvokeHistoryVO> result = new PageResult<>();
        result.setElements(content);
        result.setTotalSize(totalElements);
        return result;
    }

}
